<?php #Фильтр товаров

$gets = array();


if( isset( $_POST['br'] ) ) {  // Бренды
	foreach( $_POST['br'] as $brand_title => $brand_id ) {
		/*if( count($_POST['br']) == 1 )
			$brand_title_url = $brand_title;
		else*/
		$gets[] = 'br[]='.$brand_id;
	}
	$clause[] = '`brand_id` IN ( '.implode( ',', $_POST['br'] ).' ) ';
}


if( $_POST['mi'] != $_POST['min_price'] ) {		// Цены
	$gets[] = 'mi='.$_POST['mi'];
	$clause[] = '`price_retail` > '.$_POST['mi'];
}
if( $_POST['ma'] != $_POST['max_price'] ) {
	$gets[] = 'ma='.$_POST['ma'];
	$clause[] = '`price_retail` < '.$_POST['ma'];
}


if( isset( $_POST['ch'] ) ) {  // Характеристики
	foreach( $_POST['ch'] as $f_id => $char )
		foreach( $char as $i => $v_id )
			$gets[] = 'ch['.$f_id.'][]='.$v_id;

	$where_array = array();
	foreach( $_POST['ch'] as $field_id => $value_ids )
	{
		$where = array();
		foreach( $value_ids as $value_id ) {
			$where[] = '`field_id` = '.$field_id.' AND `value_id` = '.$value_id;
		}
		$where_array[] = '`product_code` IN ( SELECT `product_code` FROM `store_p_charact_datas` WHERE '.implode( ' OR ', $where ).' )';
	}
	$clause[] = implode( ' AND ', $where_array );
}


if( isset( $_POST['pp'] ) ) {  // Статус
	foreach( $_POST['pp'] as $pp ) {
		if( in_array( $pp , array( 0, 1 ) ) )
			$pps[$pp] = $pp;
		elseif( $pp == 3 ) {
			$pps[3] = 3;
			$pps[4] = 4;
			$pps[5] = 5;
		}
	}
	foreach( $pps as $pp )
		$gets[] = 'pp[]='.$pp;
	$clause[] = '`pp` IN ('.implode( ',', $pps ).')';
}

$clause[] = '`parents` = "'.$_POST['parents'].'"';
$sql = 'SELECT count( `product_code` ) AS `count` FROM `store_products_cache` WHERE `price_retail` > 0 AND '.implode( ' AND ', $clause );
$path = __DIR__ .'/cache/'. md5($sql).'.txt';
/*echo __DIR__;*/

/*if(file_exists($path) && (time() - filemtime($path)) <= 12*60*60) {
	$result = unserialize(file_get_contents($path));

} else {
	$conn->query($sql);
	$result = $conn->fetch();

	try {
		unlink($path);
	} catch (mysqli_sql_exception $e) {

		$error = $e;

	}

	file_put_contents($path, serialize($result));
}*/
$conn->query($sql);
$result = $conn->fetch();
$count = ( $row = $result ) ? $row->count : 0;

/*if( isset($brand_title_url) ) {
	$link_get_part = count( $gets ) ? '?'.implode( '&', $gets ).'&p=0' : '';
	$link = 'http://raybt.ru'.$_POST['url'].'/'.getGoodUrl($brand_title_url).$link_get_part;
}
else*/
$link = count( $gets ) ? '?'.implode( '&', $gets ).'&p=0' : $_POST['url'];

echo json_encode( array( 'count' => $count, 'link' => $link ) ); exit;
